import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/me/application/notification/service_product_list_notifier.dart';
import 'package:casdon/modules/me/domain/states/service_product_list_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class ServiceProductListScreen extends ConsumerStatefulWidget {
  const ServiceProductListScreen({super.key});

  @override
  ConsumerState<ServiceProductListScreen> createState() =>
      _ProductSelectionScreenState();
}

class _ProductSelectionScreenState
    extends ConsumerState<ServiceProductListScreen> {
  int _selectedCategoryIndex = 0;
  int _selectedProductIndex = 0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadInitialData();
    });
  }

  void _loadInitialData() {
    final notifier = ref.read(serviceProductListProvider.notifier);
    notifier.fetchData();
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(serviceProductListProvider);

    return Scaffold(
      appBar: CommonAppBar(title: "选择产品"),
      backgroundColor: Colors.white,
      body: Column(
        children: [
          Expanded(
            child: state.when(
              loading: () => const Center(child: CommonLoadingWidget()),
              error: (e, _) => Center(child: Text('')),
              data: (state) {
                if (state.isEmpty) {
                  return _buildEmpty();
                } else {
                  return Row(
                    children: [
                      _buildCategoryList(state),
                      _buildProductList(state),
                    ],
                  );
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmpty() {
    return Center(child: Text("没有产品相关数据"));
  }

  // ✅ 左侧分类列表
  Widget _buildCategoryList(List<ProductCategory> list) {
    return Container(
      width: 120,
      decoration: BoxDecoration(
        border: Border(right: BorderSide(color: Colors.grey.shade200)),
      ),
      child: ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) {
          final category = list[index];
          final isSelected = index == _selectedCategoryIndex;

          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedCategoryIndex = index;
                _selectedProductIndex = 0;
              });
            },
            child: Container(
              height: 50, // ✅ 固定高度匹配图片
              padding: const EdgeInsets.symmetric(horizontal: 12),
              decoration: BoxDecoration(
                color: isSelected ? Colors.white : Colors.grey.shade50,
                border: Border(
                  left: BorderSide(
                    color: isSelected
                        ? context.colorScheme.primary
                        : Colors.transparent,
                    width: 3,
                  ),
                ),
              ),
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  category.name,
                  style: TextStyle(
                    fontSize: 14,
                    color: isSelected
                        ? context.colorScheme.primary
                        : Colors.black87,
                    fontWeight: isSelected
                        ? FontWeight.w600
                        : FontWeight.normal,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // ✅ 右侧产品列表
  Widget _buildProductList(List<ProductCategory> list) {
    final selectedCategory = list[_selectedCategoryIndex];

    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              selectedCategory.name,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: ListView.builder(
                itemCount: selectedCategory.products.length,
                itemBuilder: (context, index) {
                  final product = selectedCategory.products[index];
                  final isSelected = index == _selectedProductIndex;

                  return GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedProductIndex = index;
                        context.router.maybePop(
                          list[_selectedCategoryIndex]
                              .products[_selectedProductIndex],
                        );
                      });
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(color: Colors.grey.shade200),
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            product.name,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.black87,
                              fontWeight: isSelected
                                  ? FontWeight.w600
                                  : FontWeight.normal,
                            ),
                          ),
                          if (isSelected)
                            Icon(
                              Icons.check,
                              size: 18.r,
                              color: context.colorScheme.primary,
                            ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  _onPopBack(BuildContext context, WidgetRef ref) {}
}
